package cn.cmcc.online.smsapi.sdk.db;

import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import cn.cmcc.online.smsapi.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.cmcc.online.smsapi.sdk.Iservice.XyCallBack;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.base.BaseManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.NetUtil;
import cn.cmcc.online.smsapi.sdk.net.util.ServerResposeParseUtil;
import cn.cmcc.online.smsapi.sdk.net.util.ServerUtil;
import cn.cmcc.online.smsapi.sdk.ui.popu.util.ViewUtil;
import cn.cmcc.online.smsapi.sdk.util.DateUtils;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
import cn.cmcc.online.smsapi.sdk.util.XyUtil;

public class TrainManager {
    public final static String ID = "id";

    public final static String TRAIN_NUM = "train_num";

    public final static String START_CITY = "start_city";

    public final static String END_CITY = "end_city";

    public final static String TRAIN_TYPE = "train_type";

    public final static String START_TIME = "start_time";

    public final static String END_TIME = "end_time";

    public final static String MILEAGE = "mileage";
    
    public final static String STATION_LIST = "station_list";//车站列表,jsonarray[jsonobject{"name":"",time:""},]
    
    public final static String DURATION = "duration";
    /* SDK-459/yangzhi/2016.05.26---start--- */
    public final static String DAY = "day";
    /* SDK-459/yangzhi/2016.05.26---end--- */
    public final static String DATA_TIME = "data_time";
    /* SDK-465/yangzhi/2016.05.30---start--- */
    public static final String TABLE_NAME = "tb_train6";
    public static final String DROP_OLD_TABLE = " DROP TABLE IF EXISTS tb_train ";
    /* SDK-465/yangzhi/2016.05.30---end--- */
    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;

    public static final String CREATE_TABLE = "create table  if not exists " + TABLE_NAME + 
    										  " (" + ID + " INTEGER PRIMARY KEY," 
    										  /* SDK-465/yangzhi/2016.05.30---start--- */
    										   + TRAIN_NUM + " TEXT not null," 
    										   /* SDK-465/yangzhi/2016.05.30---end--- */
    										   + START_CITY + " TEXT,"
									           + END_CITY + " TEXT," 
    										   + TRAIN_TYPE + " INTEGER default 0," 
    										   + START_TIME  + " TEXT," 
    										   + END_TIME + " TEXT," 
    										   + MILEAGE + " TEXT," 
    										   + STATION_LIST +" TEXT,"
    										   + DURATION + " TEXT" + ","
    /* SDK-459/yangzhi/2016.05.26---start--- */
    										   + DAY + " TEXT" + ","
    										   + DATA_TIME + " LONG default 0)";
    
    public static final String ADD_STATION_LIST = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+STATION_LIST+" TEXT ";
    public static final String ADD_DATA_TIME = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+DATA_TIME+" LONG default 0 ";
    public static final String ADD_DAY = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+DAY+" TEXT ";
    /* SDK-459/yangzhi/2016.05.26---end--- */
    

    /**
     * 导入火车数据 
     * 
     * @param ctx
     */
    public static void importTrainData(Context ctx) {
        SQLiteDatabase db = null;
        String path = Constant.getDRAWBLE_PATH() + "train_data.txt";
        java.io.LineNumberReader r = null;
        try {
            int channelType = ViewUtil.getChannelType();
            r = XyUtil.getLineByCompressFile(path);
            String line = null;
            db = DBManager.getSQLiteDatabase();
            db.beginTransaction();
            line = r.readLine();

            ContentValues newValues = new ContentValues();
            long rr = 0;
            // 一加、华为渠道
            if (channelType == 6 || channelType == 7) {
                while ((line = r.readLine()) != null) {

                    String[] arr = line.split("\t");
                    if (arr.length < 5) {
                        continue;
                    }

                    newValues.put(TRAIN_NUM, arr[0]);
                    newValues.put(END_CITY, arr[1]);
                    newValues.put(START_TIME, arr[2]);
                    newValues.put(END_TIME, arr[3]);
                    if (!StringUtils.isNull(arr[4])) {

                        newValues.put(STATION_LIST, arr[4]);
                    }

                    rr = db.update(TABLE_NAME, newValues, TRAIN_NUM + "=?", new String[] { arr[0] });

                    if (rr < 1) {
                        db.insert(TABLE_NAME, null, newValues);
                    }
                }
            } else {
                String trainArr[] = line.split("=");
                while ((line = r.readLine()) != null) {

                    String[] arr = line.split(" ");
                    newValues.put(TRAIN_NUM, arr[0]);
                    if (arr.length >= 2) {
                        newValues.put(END_CITY, trainArr[Integer.valueOf(arr[1])]);
                    }
                    rr = db.update(TABLE_NAME, newValues, TRAIN_NUM + "=?", new String[] { arr[0] });
                    if (rr < 1) {
                        db.insert(TABLE_NAME, null, newValues);
                    }
                }
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e(Constant.TAG, "importTrainData: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            DBManager.closeDB(path, true, r, null, db);
        }
    }

    public static boolean checkUpdateData() {

        new Thread() {
            @Override
            public void run() {
            	try {
            		importTrainData(Constant.getContext());
				} catch (Throwable e) {
					LogManager.e(Constant.TAG, e.getMessage(), e);
				}
            }
        }.start();
        return true;
    }

    public static String getEndCity(String trainNum) {
        try {
            String[] arr = null;
            if (!StringUtils.isNull(trainNum)) {
                arr = trainNum.split("/");

            }
            if (arr != null && arr.length >= 1) {
                return queryEndCity(arr[0]);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "getEndCity: ", e);

        }
        return "";

    }

    /**
     * @param trainNum
     * @return
     */
    public static String queryEndCity(String trainNum) {

        XyCursor cursor = null;
        try {
            trainNum = trainNum.replaceFirst("次", "");
            cursor = DBManager.query(TABLE_NAME, new String[] {
                END_CITY
            }, TRAIN_NUM + " = ?", new String[] {
                trainNum + ""
            });
            if (cursor != null && cursor.moveToNext()) {
                int index = cursor.getColumnIndex(END_CITY);
                return cursor.getString(index);
            }
        } catch (Throwable e) {
            // TODO Auto-generated catch block
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "queryEndCity: ", e);

        } finally {
             XyCursor.closeCursor(cursor, true);
        }
        return "";
    }

   

    /* SDK-459/yangzhi/2016.05.26---start--- */
    public static JSONObject queryTrainInfo(String trainNum, String day) {
        XyCursor cursor = null;
        JSONObject jsonObject = null;
        try {
            trainNum = trainNum.replaceFirst("次", "");
            String[] fieldArr = new String[] { ID, TRAIN_NUM, START_CITY, END_CITY, TRAIN_TYPE, START_TIME, END_TIME,
                    MILEAGE, STATION_LIST, DURATION, DAY, DATA_TIME };
            cursor = DBManager.query(TABLE_NAME, fieldArr, TRAIN_NUM + " = ? AND " + DAY + " = ? ", new String[] {
                    trainNum, day });
            jsonObject = BaseManager.loadSingleDataFromCursor(fieldArr, cursor);
        } catch (Throwable e) {
             // TODO Auto-generated catch block
//             e.printStackTrace();
             LogManager.e(Constant.TAG, "queryTrainInfo: ", e);

         } finally {
              XyCursor.closeCursor(cursor, true);
              deleteExpireTrainInfo();
         }
        
		return jsonObject;
    	
    }
    /* SDK-459/yangzhi/2016.05.26---end--- */

    /* SDK-459/yangzhi/2016.05.26---start--- */
    public static void deleteExpireTrainInfo() {
        try {
            int deleteCount = DBManager.delete(TABLE_NAME, DAY + " < ? ", new String[] { DateUtils.getTimeString(Constant.PATTERN,
                    (System.currentTimeMillis() - DexUtil.getUpdateCycleByType(
                            OnlineUpdateCycleConfigInterface.TYPE_TRAIN_DATA_CYCLE, Constant.month))) });
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "deleteExpireTrainInfo: ", e);
        }
    }
    /* SDK-459/yangzhi/2016.05.26---end--- */
    /* MEIZUIC-57/yangzhi/2016.11.02---start--- */
    private static JSONObject getTrainData(JSONObject json) {
        // 将stations格式转成STATION_LIST需要的格式
        try {
            if (json == null || !json.has("stations")) {
                return null;
            }

            JSONObject newJson = new JSONObject();
            JSONArray stations = json.getJSONArray("stations");
            JSONArray stationsNew = new JSONArray();
            JSONObject station;
            JSONObject stationNew;
            for (int i = 0; i < stations.length(); i++) {
                stationNew = new JSONObject();
                station = stations.getJSONObject(i);
                /* SAMSUNGCS-93/yangzhi/2016.04.01---start--- */
                stationNew.put("name", station.optString("cz"));
                stationNew.put("spt", station.optString("tcsj"));
                stationNew.put("stt", station.optString("kcsj"));
                stationNew.put("day", station.optString("rq"));
                stationNew.put("travel_time", station.optString("qjls"));
                /* SAMSUNGCS-93/yangzhi/2016.04.01---end--- */
                /* MEIZUIC-17 songzhirong 20160607 start */
                stationNew.put("cx", station.optString("cx"));
                /* MEIZUIC-17 songzhirong 20160607 end */
                
                /* MEIZUIC-66 zhaojiangwei 20170104 start */
                stationNew.put("tcTime", station.optLong("tcTime"));
                stationNew.put("kcTime", station.optLong("kcTime"));
                stationNew.put("lsMills", station.optLong("lsMills"));
                stationNew.put("stayMills", station.optLong("stayMills"));
                /* MEIZUIC-66 zhaojiangwei 20170104 end */
                
                stationsNew.put(stationNew);
            }
            /* SDK-459/yangzhi/2016.05.26---start--- */
            newJson.put(STATION_LIST, stationsNew);
            newJson.put(TRAIN_NUM, json.optString("cc"));
            newJson.put(START_CITY, json.optString("sfz"));
            newJson.put(END_CITY, json.optString("zdz"));
            newJson.put(TRAIN_TYPE, json.optString("lclx"));
            newJson.put(START_TIME, json.optString("fs"));
            newJson.put(END_TIME, json.optString("ds"));
            newJson.put(MILEAGE, json.optString("lc"));
            newJson.put(DURATION, json.optString("ls"));
            newJson.put(DAY, json.optString("day"));
            newJson.put(DATA_TIME, System.currentTimeMillis());

            return newJson;
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "getContentValues: ", e);
            return null;
        }
        /* MEIZUIC-57/yangzhi/2016.11.02---end--- */
        /* SDK-459/yangzhi/2016.05.26---end--- */
    }
    /* MEIZUIC-57/yangzhi/2016.11.02---start--- */
	public static ContentValues getContentValues(JSONObject json) {
		String[] valuesCols = new String[] { TRAIN_NUM, START_CITY, END_CITY,
				TRAIN_TYPE, START_TIME, END_TIME, MILEAGE, STATION_LIST,
				DURATION, DAY, DATA_TIME };
		ContentValues values = BaseManager.getContentValues(null, valuesCols,
				valuesCols, json, false);
		return values;
	}
    /* MEIZUIC-57/yangzhi/2016.11.02---end--- */

    /**
     * 根据车次在线查询数据
     * 
     * @param callBack 回调函数  无数据或异常时返回参数为null，正常情况返回参数：
     *                 index0(String):短信ID
     *                 index1(JSONObject):车次信息Json对象  
     *                                        例:{"station_list":"[{\"name\":\"重庆北\",\"spt\":\"07:48\",
     *                                        \"stt\":\"07:48\"},{\"name\":\"广安\",\"spt\":\"09:13\",\"stt\":\"09:20\"}]"}
     *                                        其中name为站点名，spt为到站时间，stt为出站时间
     *                 index2(String):车次号
     *                 index3(String):出发地
     *                 index4(String):目的地
     *                 index5(boolean):true=联网接口 false=本地接口
     * @param id 短信ID
     * @param trainNum 车次号，多个以/隔开
     * @param from 出发地
     * @param to 目的地
     */
    /* MEIZUIC-66 zhaojiangwei 20170109 start */
    public static void checkDataOnline(final XyCallBack callback, final String id, final String train_num, final String day, final String from, final String to){
         checkDataOnline(callback, id,  train_num, day, from, to, null);
    }
    /* MEIZUIC-66 zhaojiangwei 20170109 end */   
    public static void checkDataOnline(final XyCallBack callback, final String id, final String train_num, final String day, final String from, final String to, Map extend){
    	try{
    	    /*MEIZUIC-17 songzhirong 20160607 start*/
    	    /* SDK-793/yangzhi/2017.06.06---start--- */
    	    NetUtil.requestTokenIfNeed("", extend);
    	    /* SDK-793/yangzhi/2017.06.06---end--- */
            /*MEIZUIC-17 songzhirong 20160607 end*/
    		XyCallBack requestCallback=new XyCallBack() {
    			@Override
    			public void execute(Object... obj) { 
    				if(obj == null || obj.length != 2 || !obj[0].toString().equals("0")){ 
						XyUtil.doXycallBackResult(callback, id); 
						return;
    				}
    				
					SQLiteDatabase db = null;
					try {
						String response=obj[1].toString();
						JSONObject trainData = ServerResposeParseUtil.parseTrainData(response);
                        if (trainData != null && trainData.length() > 0) {
                            db = DBManager.getSQLiteDatabase();
                            String trainNum = train_num.replace("次", "");
                            trainData.put("cc", trainNum);
                            /*SDK-679 zhaojiangwei 20161118 start */
                            String trainDay = trainData.optString("date");
                            if (StringUtils.isNull(trainDay)) {
                                trainDay = day;
                            }
                            trainData.put("day", trainDay);
                            /*SDK-679 zhaojiangwei 20161118 end */
                            /* MEIZUIC-57/yangzhi/2016.11.02---start--- */
                            JSONObject newTrainData = getTrainData(trainData);
                            if (newTrainData != null) {
                                ContentValues contentValue = getContentValues(newTrainData);
                                if (contentValue != null) {
                                    BaseManager.saveOrUpdate(db, TABLE_NAME, contentValue, TRAIN_NUM + " = ? AND "
                                            + DAY + " = ? ", new String[] { trainNum, trainDay });
                                    XyUtil.doXycallBackResult(callback, id, newTrainData, train_num, from, to, true); // true:联网查询
                                    return;
                                }
                            }
                            /* MEIZUIC-57/yangzhi/2016.11.02---end--- */
                        }
						XyUtil.doXycallBackResult(callback, id); 
					} catch (Throwable e) {
//						e.printStackTrace();
			            LogManager.e(Constant.TAG, "checkDataOnline: ", e);

						XyUtil.doXycallBackResult(callback, id); 
					}finally{
						DBManager.close(db);
					}
    			}
        	};
        /* SDK-459/yangzhi/2016.05.26---end--- */
            /* SDK-793/yangzhi/2017.06.06---start--- */
            if (NetUtil.isExcludeEnhance(extend) || NetUtil.isEnhance()) {// 根据车次在线查询数据，受增强开关控制
            /* SDK-793/yangzhi/2017.06.06---end--- */
                /* SDK-504 huangzhiqiang 20160623 start */
        	    /* MEIZUIC-66 zhaojiangwei 20170109 start */  
                String ft = null;
                if (extend!=null && extend.containsKey("ft")) {
                    ft = (String) extend.get("ft");
                }
                String dataString = ServerUtil.getQueryCheciRequest(train_num.replace("次", ""), day, from,  ft);
                /* MEIZUIC-66 zhaojiangwei 20170109 end */ 
                if (!StringUtils.isNull(dataString)) {
                    NetUtil.executePubNumServiceHttpRequest(dataString, "990005", requestCallback, "", true, false,
                            NetUtil.REQ_QUERY_CHECI, false);
                } else {
                    XyUtil.doXycallBackResult(callback, id);
                }
                /* SDK-504 huangzhiqiang 20160623 end */
            }
        	else{
				XyUtil.doXycallBackResult(callback, id); 	
        	}
    	}catch(Throwable e){
//    		e.printStackTrace();
            LogManager.e(Constant.TAG, "checkDataOnline: ", e);

    	}
    }
}
